package com.hucheng.seckill.rabbitmq;

import com.alibaba.fastjson.JSONObject;
import com.hucheng.common.constant.RedisConstant;
import com.hucheng.common.utils.RedisUtils;
import com.hucheng.seckill.config.RabbitP2PConfig;
import com.hucheng.seckill.service.SeckillGoodsService;
import com.hucheng.seckill.service.SeckillOrderService;
import com.hucheng.seckill.vo.SeckillGoodsVO;
import com.hucheng.seckill.vo.SeckillOrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @Author: 凉白开不加冰
 * @Version: 0.0.1V
 * @Date: 2019-07-01
 * @Description: 秒杀商品队列消费
 **/
@Slf4j
@Component
public class SeckillReceiver {

    @Autowired
    private SeckillGoodsService seckillGoodsService;

    @Autowired
    private SeckillOrderService seckillOrderService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RabbitListener(queues = RabbitP2PConfig.SECKILL_QUEUE_NAME)
    public void receive(String msg) {
        JSONObject jsonObject = JSONObject.parseObject(msg);
        Integer goodsId = jsonObject.getInteger("goodsId");
        Integer userId = jsonObject.getInteger("userId");

        //获取秒杀商品信息
        SeckillGoodsVO seckillGoodsVO = seckillGoodsService.getSeckillGoodsByGoodsId(goodsId);
        int stock = seckillGoodsVO.getStockCount();
        if (stock <= 0) {
            log.info("==> 秒杀商品 " + goodsId + " 库存已完");
            return;
        }

        //判断用户是否已经秒杀到商品
        SeckillOrderVO seckillOrderVO = RedisUtils.get(redisTemplate, RedisConstant.SECKILL_ORDER_KEY + userId + "_" + goodsId, SeckillOrderVO.class);
        //从数据库获取订单判断
        SeckillOrderVO seckillOrderByDBVO = seckillOrderService.getUserSeckillOrderByUserId(userId, goodsId);
        if (seckillOrderVO != null || seckillOrderByDBVO != null) {
            RedisUtils.incr(redisTemplate, RedisConstant.SECKILL_GOODS_KEY + goodsId, 1);
            log.info("==> 秒杀商品 " + goodsId + " 用户已抢到");
            return;
        }

        //减库存 下订单 写入秒杀订单
        seckillGoodsService.createSeckillOrder(userId, seckillGoodsVO);
    }
}
